package cn.org.donald.framework.controller;

import cn.org.donald.framework.service.SysLoginService;
import cn.org.donald.framework.service.SysUserService;
import cn.org.donald.framework.pojo.dto.ChangePwdDto;
import cn.org.donald.framework.pojo.dto.PageDto;
import cn.org.donald.framework.pojo.dto.SmsVerifyDto;
import cn.org.donald.framework.pojo.dto.UserDto;
import cn.org.donald.framework.util.EncodeUtil;
import cn.org.donald.framework.util.RequestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import cn.org.donald.framework.constant.EncodeConstant;
import cn.org.donald.framework.constant.InfoConstant;
import cn.org.donald.framework.constant.RegisterConstant;
import cn.org.donald.framework.pojo.vo.HttpResult;
import cn.org.donald.framework.pojo.vo.TableResult;
import cn.org.donald.pojo.entity.Login;
import cn.org.donald.pojo.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @author : Donald
 * @since : 2020/11/7 16:20
 */

@RestController
@RequestMapping("/sysUser")
@Api(value = "用户管理", description = "用户管理相关功能")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysLoginService sysLoginService;

    @PostMapping("/getPage")
    @ApiOperation(value = "用户集合分页查询")
    @RequiresPermissions("sysUser:getPage:post")
    public TableResult getPage(@RequestBody PageDto<User> pageDto){
        IPage<User> page = sysUserService.findAllPage(pageDto);
        return toTableResult(page);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根据id删除用户")
    @RequiresPermissions("sysUser:delete:delete")
    public HttpResult delete(@PathVariable Long id){
        if(sysUserService.isAdminUser(id)){
            return toResultFail(InfoConstant.ADMIN_USER_EXCEPT_INFO);
        }
        int row = sysUserService.removeById(id);
        return row>0?toResultSuccess(InfoConstant.DELETE_SUCCESS):toResultFail("没有可删除的用户");
    }

    @PutMapping("/edit")
    @ApiOperation(value = "根据id编辑用户")
    @RequiresPermissions("sysUser:edit:put")
    public HttpResult edit(@RequestBody UserDto userDto){
        if (sysUserService.isAdminUser(userDto.getId())){
            return toResultFail(InfoConstant.ADMIN_USER_EXCEPT_INFO);
        }
        int rows = sysUserService.edit(userDto);
        return rows>0?toResultSuccess(InfoConstant.EDIT_SUCCESS):toResultFail(InfoConstant.EDIT_FAIL);
    }

    @PostMapping("/add")
    @ApiOperation(value = "新增管理员用户")
    @RequiresPermissions("sysUser:add:post")
    public HttpResult add(@RequestBody User user){
        if (sysUserService.isExistByUserName(user.getUserName())){
            return toResultFail(RegisterConstant.USER_NAME_EXIST);
        }
        //生成随机盐
        String saltValue = EncodeUtil.getSalt();
        //根据随机盐生成加密密码
        String encodePassword = EncodeUtil.getEncodePassword(EncodeConstant.DEFAULT_PASSWORD,saltValue);
        user.setSaltValue(saltValue);
        user.setPassword(encodePassword);
        int rows = sysUserService.insertAdminUser(user);
        return rows>0?toResultSuccess("添加成功,初始密码:"+EncodeConstant.DEFAULT_PASSWORD+",请尽快登录修改"):toResultFail(InfoConstant.ADD_FAIL);
    }

    @GetMapping("/person")
    @ApiOperation(value = "个人中心")
    public HttpResult getPerson(HttpServletRequest request){
        Long userId = RequestUtil.getUserId(request);
        User user = sysUserService.findById(userId);
        return toResultSuccess(user);
    }

    @PostMapping("/changePassword")
    @ApiOperation(value = "修改密码")
    public HttpResult changePassword(@RequestBody ChangePwdDto changePwdDto, HttpServletRequest request){
        return sysUserService.changePwd(changePwdDto,request) ? toResultSuccess("密码修改成功") : toResultFail("密码修改失败,请重新获取验证码!");
    }

    @PostMapping("/sendPhoneVerify")
    @ApiOperation(value = "发送短信验证码")
    public HttpResult verifySms(String phone,HttpServletRequest request){
        return sysUserService.sendSmsVerify(phone,request);
    }

    @PostMapping("/verifySms")
    @ApiOperation(value = "验证短信验证码")
    public HttpResult verifySms(@RequestBody SmsVerifyDto smsVerifyDto, HttpServletRequest request){
        if (EncodeUtil.verifySms(smsVerifyDto,request)){
            // 验证成功 返回获取验证状态的token
            HashMap<String, Object> map = sysUserService.verified(request);
            return toResultSuccess(map);
        }
        return toResultFail(InfoConstant.CAPTCHA_ERROR);
    }

    @GetMapping("/getLoginRecord")
    @ApiOperation(value = "获取登录记录")
    public HttpResult getLoginRecord(HttpServletRequest request){
        Long userId = RequestUtil.getUserId(request);
        QueryWrapper<Login> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        Login one = sysLoginService.getOne(queryWrapper);
        return toResultSuccess(one);
    }

    @PutMapping("/editPerson")
    @ApiOperation(value = "修改个人信息")
    public HttpResult editPerson(@RequestBody UserDto userDto){
        return sysUserService.editPerson(userDto) > 0 ? toResultSuccess(InfoConstant.EDIT_SUCCESS) : toResultFail(InfoConstant.EDIT_FAIL);
    }
}
